<style lang="less">
  @import 'login.less';
</style>

<template>
  <div class="login">
    <div class="login-con">
      <Card icon="log-in" title="欢迎登录" :bordered="false">
        <div class="form-con">
          <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
            <FormItem prop="userName">
              <Input v-model="form.username" placeholder="请输入用户名或联系电话">
                <span slot="prepend">
                  <Icon :size="16" type="ios-person"></Icon>
                </span>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="form.password" placeholder="请输入密码">
                <span slot="prepend">
                  <Icon :size="14" type="md-lock"></Icon>
                </span>
              </Input>
            </FormItem>
            <FormItem>
              <Button @click="handleSubmit" type="primary" long>登录</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
  import {mapActions} from 'vuex'

  export default {
    data() {
      return {
        form: {
          username: '',
          password: ''
        },
        ruleValidate: {
          username: [
            {required: true, message: '账号不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      rules() {
        return {
          username: this.ruleValidate.username,
          password: this.ruleValidate.password
        }
      }
    },
    methods: {
      ...mapActions([
        'handleLogin',
        'getUser'
      ]),
      handleSubmit() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            const {username, password} = this.form;
            this.handleLogin({username, password}).then(res => {
              if (res.status === 200) {
                this.getUser()
                this.$router.push({
                  name: this.$config.homeName
                })
              } else {
                this.$Message.warning('用户名或密码不正确')
              }
            }).catch(err => {
              this.$Message.warning('用户名或密码不正确')
            })
          }
        })
      }
    }
  }
</script>

<style>

</style>
